package com.core.handler;

import com.alibaba.fastjson2.JSON;
import com.core.constant.CharSetConstant;
import com.core.resp.AjaxResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : HUANG
 * @create : 2025/6/1 18:34
 * @function : 权限验证处理类
 */
@Slf4j
@Configuration
public class AccessDeniedHandlerHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.warn("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        int code = 403;
        String msg = "请求访问：{" + request.getRequestURI() + "}，权限验证失败，没有访问权限";
        response.setCharacterEncoding(CharSetConstant.CHAR_SET);
        response.getWriter().print(JSON.toJSONString(AjaxResponse.error(code, msg)));
    }
}
